package com.imooc.controller;



import com.google.gson.Gson;
import com.imooc.api.intercept.JWTCurrentUserInterceptor;
import com.imooc.base.BaseInfoProperties;
import com.imooc.grace.result.GraceJSONResult;
import com.imooc.grace.result.ResponseStatusEnum;
import com.imooc.pojo.Users;
import com.imooc.pojo.bo.RegistLoginBO;
import com.imooc.pojo.vo.UsersVO;
import com.imooc.service.UsersService;
import com.imooc.utils.IPUtil;
import com.imooc.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@RequestMapping("passport")
@Slf4j
public class PassportController extends BaseInfoProperties {

    @Autowired
    private UsersService usersService;

    @Autowired
    private JWTUtils jwtUtils;

    @PostMapping("getSMSCode")
    public GraceJSONResult getSMSCode(String mobile, HttpServletRequest request){
        if(StringUtils.isBlank(mobile)){
            return GraceJSONResult.error();
        }
        String requestIp = IPUtil.getRequestIp(request);
        redis.setnx60s(MOBILE_SMSCODE+":"+requestIp,mobile);

        String code =  (int)((Math.random()*9+1)*100000)+"";

        log.info("验证码为{}",code);
        //将验证码存入redis，用于后面的注册登录
        redis.set(MOBILE_SMSCODE+":"+mobile,code,30*60);


        return GraceJSONResult.ok();
    }


    @PostMapping("login")
    public GraceJSONResult login(@Valid @RequestBody RegistLoginBO registLoginBO){
        String mobile = registLoginBO.getMobile();
        String smsCode = registLoginBO.getSmsCode();

        //1.获取验证码
        String code = redis.get(MOBILE_SMSCODE + ":" + mobile);
        if(StringUtils.isBlank(code) || !code.equalsIgnoreCase(smsCode)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.SMS_CODE_ERROR);
        }
        //2.查询数据库，看是否已经注册过
        Users user = usersService.queryMobileIsExist(mobile);
        if(user == null ){
            //2.1 没有注册过就创建用户
            user = usersService.createUsers(mobile);
        }

        Users users = new Users();
        String id = user.getId();
        users.setId(id);
        String jwt = jwtUtils.createJWTWithPrefix(new Gson().toJson(users),
//                                                    Long.valueOf(60 * 1000),
                TOKEN_USER_PREFIX);

        // 3. 用户登录注册以后，删除redis中的短信验证码
        redis.del(MOBILE_SMSCODE + ":" + mobile);
        // 4. 返回用户信息给前端
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(user,usersVO);
        usersVO.setUserToken(jwt);
        return GraceJSONResult.ok(usersVO);
    }


    @PostMapping("logout")
    public GraceJSONResult logout(@RequestParam String userId,
                                  HttpServletRequest request) throws Exception {

        // 后端只需要清除用户的token信息即可，前端也需要清除相关的用户信息
//        redis.del(REDIS_USER_TOKEN + ":" + userId);

        return GraceJSONResult.ok();
    }



    @PostMapping("logout1")
    public GraceJSONResult logout1() throws Exception {

        Users users = JWTCurrentUserInterceptor.currentUser.get();
        System.out.println("hello中通过拦截器获得用户数据："+users);

        return GraceJSONResult.ok();
    }




}
